<?php

namespace app\api\controller;

use app\common\model\czip\IpKu;
use app\common\model\RedisKeys;
use app\common\model\RedisModel;
use app\common\model\RegisterUser;
use app\common\model\SmsChannel;
use app\common\model\SmsLog;
use app\common\model\SmsTemplate;
use app\common\model\Tools;
use think\Exception;

/**
 * 短信接口
 */
class index extends SmsBaseController
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    // 短信发送
    public function sendCode()
    {
        try {
            if (!isMobile($this->params['mobile'] ?? '')) {
                $this->error('请输入正确的手机号码');
            }

            $event = $this->params['event'] ?? 'register';
            if ($event == 'register') {
                if ((new RegisterUser())->fetchValue(['advertiser_id' => $this->advertiser['id'], 'mobile' => $this->params['mobile'], 'is_auth' => 1])) {
                    $this->error('该手机号码已注册');
                }
            }

            // TODO 频率校验
            $sms_log_model = new SmsLog();
            $ip = IpKu::getClientIp();
            $current = time();
            $where = [
                'advertiser_id' => $this->advertiser['id'],
                'mobile' => $this->params['mobile'],
                'ip' => $ip
            ];

            if ($this->advertiser['sms_minute'] > 0) {
                $where['createtime'] = ['>=', $current - 60];
                $minute_count = $sms_log_model->whereCount($where);
                if ($minute_count > $this->advertiser['sms_minute']) {
                    $this->error('发送频繁，请稍后重试');
                }
            }

            if ($this->advertiser['sms_5_minute'] > 0) {
                $where['createtime'] = ['>=', $current - 300];
                $minute_5_count = $sms_log_model->whereCount($where);
                if ($minute_5_count > $this->advertiser['sms_5_minute']) {
                    $this->error('发送频繁，请稍后重试');
                }
            }

            if ($this->advertiser['sms_hour'] > 0) {
                $where['createtime'] = ['>=', $current - 3600];
                $hour_count = $sms_log_model->whereCount($where);
                if ($hour_count > $this->advertiser['sms_hour']) {
                    $this->error('发送频繁，请稍后重试');
                }
            }
            $code = rand(1000, 9999);
            $result = (new \app\common\model\TencentSms())->sendSms($this->channel_config, $this->sms_config, '86' . $this->params['mobile'], ["$code"]);
            Tools::log('./error.log', $result);
            if ($result['Response']['SendStatusSet'][0]['Code'] != 'Ok') {
                $this->error('发送频繁，请稍候重试');
            }
            $key = RedisKeys::sendCode($this->advertiser['id'], $this->params['mobile']);
            RedisModel::db($key)->setEx($key, $this->config['sms_expire'] * 60, $code);
            $sms_log_model->add([
                'advertiser_id' => $this->advertiser['id'],
                'mobile' => $this->params['mobile'],
                'ip' => $ip,
                'code' => $code
            ]);
            $this->success('发送成功');
        } catch (Exception $exception) {
            Tools::log('./error.log', [$exception->getFile(), $exception->getLine(), $exception->getMessage()]);
            $this->error('发送失败');
        }

    }

    // 注册用户
    public function registerUser()
    {
        if (!isMobile($this->params['mobile'] ?? '')) {
            $this->error('请输入正确的手机号码');
        }

        if (!($this->params['code'] ?? '')) {
            $this->error('请输入正确的验证码');
        }
        $user_model = new RegisterUser();
        $user = $user_model->fetch(['advertiser_id' => $this->advertiser['id'], 'mobile' => $this->params['mobile']])['data'];
        if ($user) {
            if ($user['is_auth']) {
                $this->error('该手机号已存在');
            }
        }
        $user_data = [
            'advertiser_id' => $this->advertiser['id'],
            'advertiser_name' => $this->advertiser['username'],
            'mobile' => $this->params['mobile'],
            'ip' => getClientIp(),
            'is_auth' => 0,
            'source' => $this->request->url(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT']
        ];

        $key = RedisKeys::sendCode($this->advertiser['id'], $this->params['mobile']);
        $code = RedisModel::db($key)->get($key);
        if ($code != $this->params['code']) {
            if (!$user) {
                $result = $user_model->add($user_data);
                if (!$result['code'] || !$result['data']) {
                    $this->error('注册失败');
                }
            }
            $this->error('验证码错误或已过期');
        }
        $user_data['is_auth'] = 1;
        RedisModel::db($key)->del($key);
        if ($user) {
            $result = $user_model->edit(['id' => $user['id']], $user_data);
            if (!$result['code']) {
                $this->error('注册失败');
            }
        } else {
            $result = $user_model->add($user_data);
            if (!$result['code'] || !$result['data']) {
                $this->error('注册失败');
            }
        }
        $this->success('注册成功');
    }

    // 短信验证码验证
    public function checkCode()
    {
        if (!isMobile($this->params['mobile'] ?? '')) {
            $this->error('请输入正确的手机号码');
        }

        if (!($this->params['code'] ?? '')) {
            $this->error('请输入正确的验证码');
        }

        $key = RedisKeys::sendCode($this->advertiser['id'], $this->params['mobile']);
        $code = RedisModel::db($key)->get($key);
        if ($code != $this->params['code']) {
            $this->error('验证码错误或已过期');
        }
        RedisModel::db($key)->del($key);
        $this->success('验证成功');
    }


}
